[]
¶A review
fruits = ['plums', 'peaches', 'pears', 'persimmons']
fruits[0]
'plums'
fruits[1]
'peaches'
fruits[3]
'persimmons'
fruits[4]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[4], line 1 ----> 1 fruits[4] IndexError: list index out of range
fruits = ['plums', 'peaches', 'pears', 'persimmons']
fruits[-1]
'persimmons'
fruits[-3]
'peaches'
fruits[-4]
'plums'
fruits[len(fruits)-1], fruits[-1]
('persimmons', 'persimmons')
range
¶for i in range(12):
print(i)
0 1 2 3 4 5 6 7 8 9 10 11
range(5)
range(0, 5)
list(range(5))
[0, 1, 2, 3, 4]
fruits = ['apples', 'apricots', 'avacados']
for index in range(len(fruits)):
print(fruits[index])
print()
# Same as
for fruit in fruits:
print(fruit)
apples apricots avacados apples apricots avacados
list(range(4, 12))
[4, 5, 6, 7, 8, 9, 10, 11]
list(range(4, 12, 2))
[4, 6, 8, 10]
What python expression using range
would you use to create the following sequences?
1, 2, 3, 4, 5
0, 2, 4, 6, 8
-6, -3, 0, 3, 6
5, 4, 3, 2
list(range(1, 6))
[1, 2, 3, 4, 5]
list(range(0, 10, 2))
[0, 2, 4, 6, 8]
list(range(-6, 9, 3))
[-6, -3, 0, 3, 6]
list(range(1.1, 6.6, 1.1))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 list(range(1.1, 6.6, 1.1)) TypeError: 'float' object cannot be interpreted as an integer
list(range(5, 1, -1))
[5, 4, 3, 2]
bears = ['brown','black','polar','koala']
bears
['brown', 'black', 'polar', 'koala']
bears[3]
'koala'
bears[3] = 'panda'
bears[3]
'panda'
bears
['brown', 'black', 'polar', 'panda']
How do these functions compare?
def large_value_of_two(items):
"""Replace 2 with something bigger (like 5)"""
new_items = []
for item in items:
if item == 2:
item = 5
new_items.append(item)
return new_items
def large_value_of_2(items):
"""Replace 2 with something bigger (like 5)"""
for i in range(len(items)):
if items[i] == 2:
items[i] = 5
numbers = [1, 2, 3, 4]
print("Numbers before:", numbers)
first_return = large_value_of_two(numbers)
print("Numbers after:", numbers)
print("large_value_of_two returned:", first_return)
print()
print("Numbers before:", numbers)
second_return = large_value_of_2(numbers)
print("Numbers after:", numbers)
print("large_value_of_2 returned:", second_return)
Numbers before: [1, 2, 3, 4] Numbers after: [1, 2, 3, 4] large_value_of_two returned: [1, 5, 3, 4] Numbers before: [1, 2, 3, 4] Numbers after: [1, 5, 3, 4] large_value_of_2 returned: None
Just because a function can change a list doesn't mean it should.
Prefer immutability whenever possible: only change inputs when there is a clear advantage over making a copy
Clearly define and document the intent of your functions.
edits.py
¶score_board.py
¶[]
range